package com.zivwu.utils.device;

import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.util.Pair;
import androidx.core.view.ViewCompat;
import androidx.fragment.app.Fragment;
import androidx.transition.AutoTransition;
import androidx.transition.Explode;
import androidx.transition.Fade;
import androidx.transition.Slide;
import androidx.transition.Transition;

import java.util.Random;

public class TransitionHelper {

    @SuppressWarnings("unchecked")
    public static Bundle getShareBundle(AppCompatActivity activity, View... views) {
        Pair<View, String>[] pairs = getPairs(views);
        return ActivityOptionsCompat.makeSceneTransitionAnimation(activity, pairs).toBundle();
    }


    /**
     * 为 v4 的 fragment添加默认，随机动画
     *
     * @param fragment fragment
     */
    public static void addAnim(Fragment fragment) {
        Transition randomAnim = getRandomAnim();
        fragment.setEnterTransition(randomAnim);
        fragment.setExitTransition(randomAnim);
        AutoTransition autoTransition = new AutoTransition();
        fragment.setSharedElementEnterTransition(autoTransition);
    }


    public static Transition getRandomAnim() {
        Transition transition;
        Random random = new Random();
        int i = random.nextInt(3);
        switch (i) {
            case 0:
                transition = new Explode();
                break;
            case 1:
                transition = new Slide();
                break;
            case 2:
                transition = new Fade();
                break;
            default:
                transition = new Explode();
                break;
        }
        return transition;
    }

    public static Pair<View, String>[] getPairs(View... views) {
        Pair<View, String>[] pairs = null;
        if (views != null) {
            pairs = new Pair[views.length];
            for (int i = 0; i < views.length; i++) {
                View view = views[i];
                pairs[i] = new Pair<View, String>(view, ViewCompat.getTransitionName(view));
            }
        }
        return pairs;
    }
}
